//
//  HSLoginController.swift
//  HomeSchoolDemo
//
//  Created by rimi on 16/9/29.
//  Copyright © 2016年 赖虹宇. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD


class HSLoginController: UIViewController {
    //账号输入框--fileprivate 设置为私有
    @IBOutlet fileprivate weak var loginAccountT: UITextField!
    //密码输入框
    @IBOutlet fileprivate weak var loginPasswordT: UITextField!
    //登录按钮
    @IBOutlet fileprivate weak var loginBtn: UIButton!
    
    //懒加载一个活动指示器
    lazy var activity : UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置UI
        setupUI()
        //懒加载一个活动指示器
        activity.center = view.center
        activity.color = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
        view.addSubview(activity)
        
    }
    //设置UI
   fileprivate func setupUI(){
        //设置圆角半径
        loginBtn.layer.cornerRadius = 5
        //设置边框
        loginBtn.layer.borderColor = UIColor.gray.cgColor
        loginBtn.layer.borderWidth = 1
    //设置输入框左边视图
    loginAccountT.leftView = setupLeftView(imageName: "icon_user")
    loginAccountT.leftViewMode = .always
    loginPasswordT.leftView = setupLeftView(imageName: "icon_password")
    loginPasswordT.leftViewMode = .always
        
    }
    //封装文本输入框左边视图
    fileprivate func setupLeftView(imageName:String) -> UIView{
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
        //第一张图片视图
        let firstV = UIImageView(image: UIImage(named: imageName))
        firstV.center = CGPoint(x: firstV.bounds.width/2 + 10, y: 22)
        bgView.addSubview(firstV)
        //第二张图片
        let towV = UIImageView(image: UIImage(named: "line_edit_sep"))
        towV.center = CGPoint(x: firstV.frame.maxX + towV.bounds.width/2 + 10, y: 22)
        bgView.addSubview(towV)
        return bgView
    }
   
    //登录按钮点击事件
    @IBAction func loginBtnClicked(_ sender: UIButton) {
        //先判断用户是否已经设置服务器ip地址
        if  baseURLStr == nil || baseURLStr! == "zao/interface/" {
            SVProgressHUD.showInfo(withStatus: "请先设置学校服务器的ip地址")
            return
        }
        guard let acc = loginAccountT.text,acc != "" else {
            //延时退出
            SVProgressHUD.setMinimumDismissTimeInterval(1.5)
            //弹窗提醒用户账号为空
            SVProgressHUD.showInfo(withStatus: "账号不能为空")
      
            return
        }
        guard let pass = loginPasswordT.text,pass != ""  else {
            //延时退出
            SVProgressHUD.setMinimumDismissTimeInterval(1.5)
            //弹窗提醒用户账号为空
            SVProgressHUD.showInfo(withStatus: "账号不能为空")

            return
        }
         //开启活动指示器
         activity.startAnimating()
        
        //拼接地址
        let urlStr = baseURLStr! + "ZH-schoolname-S-login"
        //参数字典
        let param = ["code":acc,"password":pass]
        HSNetwordTools.shared.downloadData(urlStr: urlStr, parameters: param) {[weak self] (data, error) in
            //通过闭包把数据传送过来
            if error != nil{
                self?.activity.stopAnimating()
                //延时退出
                SVProgressHUD.setMinimumDismissTimeInterval(1.5)
                //弹窗提醒用户账号为空
                SVProgressHUD.showInfo(withStatus: "网络请求失败，请检查您的网络连接状况")
                return
            }
           //获得返回的数据
            //将类型转换为Int
            guard let dict = data as?  NSDictionary else{
                return
            }
            let result = dict["result"] as! Int
            
            switch result {
            case 0:
                print(saveUserInfoPath)
                 //保存数据
                dict.write(toFile: saveUserInfoPath, atomically: true)
                
                
                //账号密码正确跳转
                self?.activity.stopAnimating()
                //获得下一个页面控制器,这样就不会保存当前界面
                UIApplication.shared.keyWindow?.rootViewController = HSDrawerController()
                //记录登录状态
                UserDefaults.standard.set(true, forKey: isLogin)
                
            case 1:
                self?.activity.stopAnimating()
                //延时退出
                SVProgressHUD.setMinimumDismissTimeInterval(1.5)
                //弹窗提醒用户账号为空
                SVProgressHUD.showInfo(withStatus: "账号或密码错误")
            default:
                break
            }
            
        }

    }
   //设置按钮点击事件
    @IBAction func loginSettingBtnClicked(_ sender: UIButton) {
        //弹窗输入服务器地址
        let alertVc = UIAlertController(title: "请输入学校服务器的ip地址", message: nil, preferredStyle: .alert)
        //添加文本输入框
        alertVc.addTextField { (textField) in
            textField.placeholder = "请输入ip地址"
            textField.borderStyle = .roundedRect
            textField.textAlignment = .center
            //先获得保存的内容并显示
            let saveIpText = UserDefaults.standard.value(forKey: HS_ipKey)
            textField.text = saveIpText as? String
        }
        //添加确定按钮
        alertVc.addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) in
            //获得输入框的内容
            let ipText = alertVc.textFields?[0].text
            //保存字符串  //key保存在公共类里面
            UserDefaults.standard.set(ipText, forKey: HS_ipKey)
        }))
        //添加取消按钮
        alertVc.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        present(alertVc, animated: true, completion: nil)
    }
    
   
    
    //调整状态栏模式
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }
    
    
     //弹窗方法
    func alert(str:String){
        
    }
  
}
//延展
extension HSLoginController{
    //回收键盘
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
       view.endEditing(true)
    }
}
